package stock;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.Session;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.csvreader.CsvReader;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import stock.model.LTModel;

@Component
@SuppressWarnings("all")
public class StockServiceImpl implements StockServiceInterface {

	@SuppressWarnings("unused")
	@Autowired
	private ProjectSession projectSession;

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private StockSelect stockselect;

	/**
	 * 深圳的excl数据
	 * 
	 */
	@Transactional
	@Scheduled(cron = "0 45 17 * * ?")
	// @Scheduled(cron = "0 49 10 * * ?")
	@Override
	public void addSz() {

		HttpDownloadFile hdf = new HttpDownloadFile();
		String date1 = DateTools.getCurrentDate("");// "2024-04-08";//
		String date2 = DateTools.getCurrentDate("");// "2024-04-08";//
//		String date1 = "2023-04-11";
//		String date2 = "2023-04-11";
		String date3 = DateTools.getCurrentYear() + "-" + DateTools.getCurrentMonth() + "-" + "01";
		String date4 = date3.substring(0, 10);
		Random r = new Random();
		double d = r.nextDouble();
		String url = "http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1815_stock_snapshot&TABKEY=tab1&txtBeginDate=" + date1 + "&txtEndDate=" + date2 + "&archiveDate=" + date3 + "&random=" + d;
		// http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1815_stock_snapshot&TABKEY=tab1&txtBeginDate=2024-04-08&txtEndDate=2024-04-08&archiveDate=2022-04-01&random=0.3052556525728731
		// String url
		// ="http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1815_stock_snapshot&TABKEY=tab1&txtBeginDate="+date1+"&txtEndDate="+date2+"&archiveDate=2022-04-01&random="+d;

		System.out.println(url);
		File f = new File("D:/stockdown/");
		File f1 = new File("/opt/stockdown/");
		String donwfile = "";
		if (f.exists()) {
			donwfile = "D:/opt/stockdown" + DateTools.getCurrentDate("") + ".csv";
		} else {

			donwfile = "/opt/stockdown/" + DateTools.getCurrentDate("") + ".csv";
		}
		try {
			hdf.down(url, donwfile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("下载深圳的EXCL出错");
		}
		System.out.println("下载" + DateTools.getCurrentDate("") + "成功" + Common.getTime());
		File f2 = new File(donwfile);
		List<Stock> listStock = null;
		if (f2.exists()) {
			try {
				listStock = read(donwfile);
			} catch (IOException e) {
				e.printStackTrace();
				// TODO Auto-generated catch block
				System.out.println("读excl错误,深圳");
			}
		}
		Session session = ContextUtil.getSessionFactory1().openSession();
		session.beginTransaction();
		String deletesql = "delete from stock where date =" + DateTools.getCurrentDate("").replace("-", "") + " and diqv =1";
		session.createSQLQuery(deletesql).executeUpdate();
		session.getTransaction().commit();
		session.clear();
		session.beginTransaction();
		// String sql = "from Stock t where t.code = ?0 and t.date = ?1";
		for (int i = 0; i < listStock.size(); i++) {
//			System.out.println(listStock.get(i).getCode());
//			List<Stock> list = session.createQuery(sql).setParameter(0, listStock.get(i).getCode())
//					.setParameter(1, listStock.get(i).getDate()).list();
//			if (list.size() > 0) {
//				Stock s = list.get(0);
//				s.setName(listStock.get(i).getName());
//				s.setChengjiaoliang(listStock.get(i).getChengjiaoliang());
//				s.setDanqianjia(listStock.get(i).getDanqianjia());
//				s.setZhandifu(listStock.get(i).getZhandifu());
//				s.setDiqv("1");
//				s.setCreateTime(DateTools.getCurrentDateTime());
//				session.update(s);
//			} else {
//				listStock.get(i).setCreateTime(DateTools.getCurrentDateTime());
//				session.save(listStock.get(i));
//			}
			listStock.get(i).setCreateTime(DateTools.getCurrentDateTime());
			session.save(listStock.get(i));

		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	public static List<Stock> read(String filePath) throws FileNotFoundException, IOException {
		List<Stock> list = new ArrayList<Stock>();
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(filePath));
		System.out.println("xssfWorkbook对象：" + xssfWorkbook);
		// 读取第一个工作表
		XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
		System.out.println("sheet对象：" + sheet);
		// 获取最后一行的num，即总行数。此处从0开始计数
		int maxRow = sheet.getLastRowNum();
		System.out.println("总行数为：" + (maxRow + 1));
		for (int row = 0; row <= maxRow; row++) {
			if (row == 0) {
				continue;
			}
			if (sheet.getRow(row).getCell(0).toString().length() <= 0) {
				break;
			}
			// System.out.print(sheet.getRow(row).getCell(cell) + " ");
			Stock stock = new Stock();
			for (int cell = 0; cell <= sheet.getRow(row).getLastCellNum() - 1; cell++) {
				if (cell == 0) {
					String date = sheet.getRow(row).getCell(0).toString();
					date = date.replace("-", "");
					stock.setDate(Integer.valueOf(date));
				}
				if (cell == 1) {
					stock.setCode(sheet.getRow(row).getCell(1).toString());
				}
				if (cell == 2) {
					stock.setName(sheet.getRow(row).getCell(2).toString());
				}
				if (cell == 7) {
					stock.setDanqianjia(Float.parseFloat(sheet.getRow(row).getCell(7).toString()));
				}
				if (cell == 9) {
					String str = sheet.getRow(row).getCell(9).toString();
					str = str.replace(",", "").replace(".", "");
					// System.out.println(str);
					if (str.length() > 0) {
						stock.setChengjiaoliang(Long.parseLong(str));
					} else {
						stock.setChengjiaoliang(0L);
					}
				}
				if (cell == 8) {
					stock.setZhandifu(Float.parseFloat(sheet.getRow(row).getCell(8).toString().replace(",", "")));
				}
				if (cell == 10) {
					stock.setCjje(Float.parseFloat(sheet.getRow(row).getCell(10).toString().replace(",", "")) + "");
				}
				stock.setDiqv("1");
			}
			list.add(stock);
		}
		return list;
	}

	/**
	 * 上海的列表数据
	 */
	@Transactional
	// @Scheduled(cron = "0 23 11 * * ?")
	@Scheduled(cron = "0 30 17 * * ?")
	// @Scheduled(cron = "0 0/5 * * * ?")
	@Override
	public void addSH() {
		System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
		final WebClient webClient = new WebClient(BrowserVersion.CHROME);// 新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
		webClient.getOptions().setThrowExceptionOnScriptError(false);// 当JS执行出错的时候是否抛出异常, 这里选择不需要
		webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);// 当HTTP的状态非200时是否抛出异常, 这里选择不需要
		webClient.getOptions().setActiveXNative(false);
		webClient.getOptions().setCssEnabled(false);// 是否启用CSS, 因为不需要展现页面, 所以不需要启用
		webClient.getOptions().setJavaScriptEnabled(true); // 很重要，启用JS
		webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 很重要，设置支持AJAX
		// webClient.getOptions().setThrowExceptionOnScriptError(true);
		webClient.setJavaScriptErrorListener(new MyJSErrorListener());
		HtmlPage page = null;
		try {
			page = webClient.getPage("http://www.sse.com.cn/market/price/report/");// 尝试加载上面图片例子给出的网页
		} catch (Exception e) {
			e.printStackTrace();
		}
		webClient.setJavaScriptTimeout(6000);
		webClient.waitForBackgroundJavaScript(6000);// 异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束

		try {
			Thread.sleep(4000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Iterable<DomNode> list1 = page.getByXPath("//tbody//tr");
		Iterable<DomNode> date = page.getByXPath("//span[@class='new_date']");
		String datec = "";
		if (date.iterator().hasNext()) {
			String str = date.iterator().next().asNormalizedText();
			datec = str.replace("更新时间：", "").substring(0, 10);

		}
		HtmlElement div = null;
		HtmlElement button = null;
		List<Stock> listall = new ArrayList<Stock>();
		saveCode(list1, listall, datec);
		try {
			for (int i = 0; i < 90; i++) {
				div = (HtmlElement) (page.getByXPath("//li[@class='next']").get(0));
				button = (HtmlElement) div.getFirstChild();
				button.click();
				page = null;
				page = button.click();
				webClient.waitForBackgroundJavaScript(3000);
				Thread.sleep(4000);
				Iterable<DomNode> list2 = page.getByXPath("//tbody//tr");
				saveCode(list2, listall, datec);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String deletesql = "delete from stock where date =" + DateTools.getCurrentDate("").replace("-", "") + " and diqv =0";

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		session1.beginTransaction();
		session1.createSQLQuery(deletesql).executeUpdate();
		session1.getTransaction().commit();
		session1.clear();
		session1.close();

		// String sql = "from Stock t where t.code = ?0 and t.date = ?1";
		for (int i = 0; i < listall.size(); i++) {
			Session session = ContextUtil.getSessionFactory1().openSession();
			session.beginTransaction();
//			List<Stock> list = session.createQuery(sql).setParameter(0, listall.get(i).getCode())
//					.setParameter(1, listall.get(i).getDate()).list();
//			if (list.size() > 0) {
//				Stock s = list.get(0);
//				s.setChengjiaoliang(listall.get(i).getChengjiaoliang());
//				s.setDanqianjia(listall.get(i).getDanqianjia());
//				s.setZhandifu(listall.get(i).getZhandifu());
//				s.setCreateTime(DateTools.getCurrentDateTime());
//				session.update(s);
//			} else {
//				listall.get(i).setCreateTime(DateTools.getCurrentDateTime());
//				session.save(listall.get(i));
//			}
			listall.get(i).setCreateTime(DateTools.getCurrentDateTime());
			session.save(listall.get(i));
			session.getTransaction().commit();
			session.clear();
			session.close();
		}

	}

	/**
	 * 上海的一页数据
	 * 
	 * @param list2
	 */
	public void saveCode(Iterable<DomNode> list2, List<Stock> listall, String datec) {
		for (DomNode domNode : list2) {
			List<DomNode> listTD = domNode.getChildNodes();
			Stock sc = new Stock();
			boolean b = false;
			for (int j = 0; j < listTD.size(); j++) {
				String string = listTD.get(j).asNormalizedText();
				if (j == 4 || j == 7 || j == 5) {
					try {
						Float.parseFloat(string.replace("%", ""));
					} catch (Exception e) {
						System.out.println("发现在一次转换错误：code==" + string);
						continue;
					}
				}
				sc.setDate(Integer.valueOf(DateTools.getCurrentDate("").replace("-", "")));
				if (j == 3) {
					if ("主板B股".equals(string)) {
						b = true;
						break;
					}
					if ("科创板".equals(string)) {
						b = true;
						break;
					}
				}
				if (j == 2) {

					sc.setName(string);
				}
				if (j == 1) {
					sc.setCode(string);
				}
				if (j == 4) {
					sc.setDanqianjia(Float.valueOf(string.replace("%", "")));
				}
				if (j == 7) {
					sc.setChengjiaoliang(Long.valueOf(string));
				}
				if (j == 7) {
					sc.setCjje(string);
				}
				if (j == 5) {
					sc.setZhandifu(Float.valueOf(string.replace("%", "")));
				}
				sc.setDiqv("0");
			}
			if (b == false) {
				listall.add(sc);
			}

		}

	}

	/**
	 * 
	 * 拉取上海换手率
	 * 
	 * @param code
	 * @return
	 */
	@Transactional
	// @Scheduled(cron = "0 0 2 * * ?")
	// @Scheduled(cron = "0 0/2 * * * ?")
	@Override
	public void addSSHuanshulv() {
		Session session = ContextUtil.getSessionFactory1().openSession();
		session.beginTransaction();
		String sql = "select DISTINCT(code) from Stock t where t.diqv = ?0";
		List<String> list = session.createQuery(sql).setParameter(0, "1").list();
		String sql1 = "from Stock t where t.code = ?0 and t.date = ?1";
		for (int i = 0; i < list.size(); i++) {
			String code = list.get(i);
			String[] f = getSSHuanshoulv(code);
			List<Stock> list1 = session.createQuery(sql).setParameter(0, code).setParameter(1, f[1]).list();
			if (list1.size() > 0) {
				Stock stock = list1.get(0);
				stock.setHuanshoulv(Float.valueOf(f[0]));
				session.update(stock);
			}
		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	public String[] getSSHuanshoulv(String code) {
		String[] str = new String[2];
		System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
		final WebClient webClient = new WebClient(BrowserVersion.CHROME);// 新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
		webClient.getOptions().setThrowExceptionOnScriptError(false);// 当JS执行出错的时候是否抛出异常, 这里选择不需要
		webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);// 当HTTP的状态非200时是否抛出异常, 这里选择不需要
		webClient.getOptions().setActiveXNative(false);
		webClient.getOptions().setCssEnabled(false);// 是否启用CSS, 因为不需要展现页面, 所以不需要启用
		webClient.getOptions().setJavaScriptEnabled(true); // 很重要，启用JS
		webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 很重要，设置支持AJAX
		webClient.getOptions().setThrowExceptionOnScriptError(false);
		webClient.setJavaScriptErrorListener(new MyJSErrorListener());
		HtmlPage page = null;
		try {
			page = webClient.getPage("http://www.sse.com.cn/assortment/stock/list/info/company/index.shtml?COMPANY_CODE=" + code);// 尝试加载上面图片例子给出的网页
		} catch (Exception e) {
			e.printStackTrace();
		}
		webClient.setJavaScriptTimeout(6000);
		webClient.waitForBackgroundJavaScript(6000);// 异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束
		Iterable<DomNode> list1 = page.getByXPath("//table[@class='table']//tbody//tr");
		int temp = 0;
		for (DomNode domNode : list1) {
			// System.out.println(domNode.asNormalizedText());
			List<DomNode> listTD = domNode.getChildNodes();
			for (int i = 0; i < listTD.size(); i++) {
				if (temp == 9) {
					str[0] = listTD.get(i).asNormalizedText().replace("%", "");
					// return Float.valueOf(listTD.get(i).asNormalizedText().replace("%", ""));
				}
				temp++;
			}
		}
		Iterable<DomNode> list2 = page.getByXPath("//h1[@class='title_lev1']//span");
		int temp1 = 0;
		for (DomNode domNode : list2) {
			if (temp1 == 1) {
				System.out.println(domNode.asNormalizedText().substring(0, 10));
				str[1] = domNode.asNormalizedText().substring(0, 10);
			}
			temp1++;
		}
		return str;
	}

	/**
	 * 深圳的300数据
	 */
	@Override
	public void addSz1() {

		HttpDownloadFile hdf = new HttpDownloadFile();
		for (int k = 0; k < 100; k++) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Date date0 = DateTools.getDateOffset(new Date(), -k);
			String date1 = DateTools.getFormatDate(date0);
			String date4 = "2023-04-01";
			Random r = new Random();
			double d = r.nextDouble();
			String url = "http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1815_stock_snapshot&TABKEY=tab1&txtBeginDate=" + date1 + "&txtEndDate=" + date1 + "&archiveDate=" + date4 + "&random=" + d;
			File f = new File("D:/stockdown/");
			File f1 = new File("/opt/stockdown/");
			String donwfile = "";
			if (f.exists()) {
				donwfile = "D:/stockdown" + date1 + ".csv";
			}
			if (f1.exists()) {
				donwfile = "/opt/stockdown/" + date1 + ".csv";
			}

			try {
				hdf.down(url, donwfile);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("下载深圳的EXCL出错");
			}
			System.out.println("下载" + date1 + "成功");
		}
		for (int k = 0; k < 100; k++) {
			Date date0 = DateTools.getDateOffset(new Date(), -k);
			String date1 = DateTools.getFormatDate(date0);
			File f = new File("D:/stockdown/");
			File f1 = new File("/opt/stockdown/");
			String donwfile = "";
			if (f.exists()) {
				donwfile = "D:/stockdown" + date1 + ".csv";
			}
			if (f1.exists()) {
				donwfile = "/opt/stockdown/" + date1 + ".csv";
			}
			File f2 = new File(donwfile);
			List<Stock> listStock = null;
			if (f2.exists()) {
				try {
					listStock = read(donwfile);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("读excl错误,深圳");
				}
			}
			Session session = ContextUtil.getSessionFactory1().openSession();
			session.beginTransaction();
			String sql = "from Stock t where t.code = ?0 and t.date = ?1";
			for (int i = 0; i < listStock.size(); i++) {
				List<Stock> list = session.createQuery(sql).setParameter(0, listStock.get(i).getCode()).setParameter(1, listStock.get(i).getDate()).list();
				if (list.size() > 0) {
					Stock s = list.get(0);
					s.setName(listStock.get(i).getName());
					s.setChengjiaoliang(listStock.get(i).getChengjiaoliang());
					s.setDanqianjia(listStock.get(i).getDanqianjia());
					s.setZhandifu(listStock.get(i).getZhandifu());
					s.setDiqv("1");
					s.setCreateTime(DateTools.getCurrentTime());
					session.update(s);
				} else {
					listStock.get(i).setCreateTime(DateTools.getCurrentTime());
					session.save(listStock.get(i));
				}

			}
			session.getTransaction().commit();
			session.clear();
			session.close();
		}
	}

	/**
	 * 深圳的300数据
	 */
	@Override
	public void addSz2() {

		for (int k = 0; k < 100; k++) {
			Date date0 = DateTools.getDateOffset(new Date(), -k);
			String date1 = DateTools.getFormatDate(date0);
			File f = new File("D:/stockdown/");
			File f1 = new File("/opt/stockdown/");
			String donwfile = "";
			if (f.exists()) {
				donwfile = "D:/stockdown" + date1 + ".csv";
			}
			if (f1.exists()) {
				donwfile = "/opt/stockdown/" + date1 + ".csv";
			}
			File f2 = new File(donwfile);
			List<Stock> listStock = null;
			if (f2.exists()) {
				try {
					listStock = read(donwfile);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					System.out.println("读excl错误,深圳");
				}
			}
			Session session = ContextUtil.getSessionFactory1().openSession();
			session.beginTransaction();
			String sql = "from Stock t where t.code = ?0 and t.date = ?1";
			for (int i = 0; i < listStock.size(); i++) {
				List<Stock> list = session.createQuery(sql).setParameter(0, listStock.get(i).getCode()).setParameter(1, listStock.get(i).getDate()).list();
				if (list.size() > 0) {
					Stock s = list.get(0);
					s.setName(listStock.get(i).getName());
					s.setChengjiaoliang(listStock.get(i).getChengjiaoliang());
					s.setDanqianjia(listStock.get(i).getDanqianjia());
					s.setZhandifu(listStock.get(i).getZhandifu());
					s.setDiqv("1");
					session.update(s);
				} else {
					session.save(listStock.get(i));
				}

			}
			session.getTransaction().commit();
			session.clear();
			session.close();
		}
	}

	/**
	 * 上海的300数据
	 */
	@Override
	public void addSH1() {

		Session session = ContextUtil.getSessionFactory1().openSession();
		String sql = "select DISTINCT(t.code),name from Stock t where t.diqv='0'";
		List<Object[]> list = session.createQuery(sql).list();
		String sql1 = "from Stock t where t.date = ?0 and t.code = ?1";

		for (int k = 0; k < list.size(); k++) {
			Session session1 = ContextUtil.getSessionFactory1().openSession();
			session1.beginTransaction();
			Object[] obj = list.get(k);
			String code = obj[0] + "";
			String name = obj[1] + "";
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpGet post = new HttpGet("http://yunhq.sse.com.cn:32041/v1/sh1/dayk/" + code + "?callback=jQuery1124019642798431642916_1680766507262&begin=-1000&end=-1&period=day&_=1680766507265");
			HttpResponse response;
			try {
				response = httpClient.execute(post);
				HttpEntity entity = response.getEntity();
				String data = EntityUtils.toString(entity);
				String content = data.substring(data.indexOf("(") + 1, data.length() - 1);
				JSONArray jsonarray = JSONObject.fromObject(content).getJSONArray("kline");
				LocalDate currentDate = LocalDate.now();
				// 获取前90天日期
				LocalDate previousDate = currentDate.minusDays(100);
				// 以6位整数格式表示日期
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
				String previousDateStr = previousDate.format(formatter);
				for (int i = 0; i < jsonarray.size(); i++) {
					if (i == 0) {
						continue;
					}
					JSONArray jsonarray0 = JSONArray.fromObject(jsonarray.get(i - 1));// 昨天
					JSONArray jsonarray1 = JSONArray.fromObject(jsonarray.get(i));// 今天
					Float f = Float.valueOf(jsonarray1.getString(4));
					Float f1 = Float.valueOf(jsonarray0.getString(4));
					Float f2 = (f - f1) / f1 * 100;
					NumberFormat numberInstance = NumberFormat.getNumberInstance();
					numberInstance.setMaximumFractionDigits(2);
					numberInstance.setRoundingMode(RoundingMode.HALF_UP);
					String fs2 = numberInstance.format(f2);
					System.out.println("日期" + jsonarray1.getString(0) + "--当前价" + jsonarray1.getString(4) + "--成交量" + jsonarray1.getString(5) + "--涨跌幅度:" + fs2);
					int date = Integer.valueOf(jsonarray1.getString(0));

					if (date < Integer.parseInt(previousDateStr)) {
						continue;
					}
					Float dangqianjia = Float.valueOf(jsonarray1.getString(4));
					Long chengjiaoliang = Long.valueOf(jsonarray1.getString(5));
					Float zhangdiefu = Float.valueOf(fs2);

					Stock stock0 = (Stock) session1.createQuery(sql1).setParameter(0, date).setParameter(1, code).uniqueResult();
					if (null != stock0) {

					} else {
						Stock stock = new Stock();
						stock.setCode(code);
						stock.setChengjiaoliang(chengjiaoliang);
						stock.setZhandifu(zhangdiefu);
						stock.setDanqianjia(dangqianjia);
						stock.setDate(date);
						stock.setName(name);
						stock.setDiqv("0");
						session1.save(stock);
					}
				}
				session1.getTransaction().commit();
				session1.clear();
				session1.close();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	/**
	 * 上海的列表数据数据每天同步，需要删掉节假日的。
	 */
	@Transactional
	@Scheduled(cron = "0 30 18 * * ?")
	// @Scheduled(cron = "0 0/5 * * * ?")
	@Override
	public void deleteSH() {

		System.out.println("-----------删除无用数据-------------");
		Session session1 = ContextUtil.getSessionFactory1().openSession();

		List<Integer> list = session1.createSQLQuery("select DISTINCT(t.date) from stock t where t.diqv =1 order by t.date desc").getResultList();
		List<Integer> list1 = session1.createSQLQuery("select DISTINCT(t.date) from stock t where t.diqv =0 order by t.date desc").getResultList();

		List<Integer> list2 = new ArrayList<Integer>();
		for (int i = 0; i < list1.size(); i++) {
			if (!list.contains(list1.get(i))) {
				list2.add(list1.get(i));
			}
		}
		session1.beginTransaction();
		System.out.println(JSONArray.fromObject(list2).toString());
		for (int i = 0; i < list2.size(); i++) {
			String deletesql = "delete from stock where diqv = 0 and date = " + list2.get(i);
			session1.createSQLQuery(deletesql).executeUpdate();
		}
		String deletetui0 = "delete from stock where name like '%退%' ";
		session1.createSQLQuery(deletetui0).executeUpdate();

		String deletetui1 = "delete from stock where name like '%ST%' ";
		session1.createSQLQuery(deletetui1).executeUpdate();

		String deletetui12 = "delete from stock where name like '%01%' ";
		session1.createSQLQuery(deletetui12).executeUpdate();

		String deletetui13 = "delete from stock where name like '%B' ";
		session1.createSQLQuery(deletetui13).executeUpdate();

		String deletetui14 = "delete from stock where name like '%02%' ";
		session1.createSQLQuery(deletetui14).executeUpdate();

		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		System.out.println("-----------删除无用数据完成-------------");
	}

	/**
	 * 周日下午3点更新的呢的概念
	 */
	@Transactional
	@Scheduled(cron = "0 0 3 ? * SAT")
	@Override
	public void addGN() {
		Session session = ContextUtil.getSessionFactory1().openSession();
		String sql = "select DISTINCT(code),t.diqv from Stock t ";
		List<Object[]> list = session.createQuery(sql).list();
		String sql1 = "from StockGaiNian t where t.code = ?0 ";
		for (int i = 0; i < list.size(); i++) {

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {

				Object[] obj = list.get(i);
				System.out.println(obj[0]);
				session.beginTransaction();
				StockGaiNian sg = (StockGaiNian) session.createQuery(sql1).setParameter(0, obj[0]).uniqueResult();
				if (sg == null) {
					sg = new StockGaiNian();
					sg.setCode(obj[0] + "");
					String code = "";
					if ("0".equals(obj[1])) {
						code = "sh" + obj[0];
					} else {
						code = "sz" + obj[0];
					}
					String[] allgn = getGN(code);
					sg.setGn(allgn[0]);
					sg.setLt(allgn[1]);
					sg.setCreateTime(DateTools.getCurrentDateTime());
					session.save(sg);
				} else {
					sg.setCode(obj[0] + "");
					String code = "";
					if ("0".equals(obj[1])) {
						code = "sh" + obj[0];
					} else {
						code = "sz" + obj[0];
					}
					String[] allgn = getGN(code);
					sg.setGn(allgn[0]);
					sg.setLt(allgn[1]);
					sg.setCreateTime(DateTools.getCurrentDateTime());
					session.merge(sg);
				}

				session.getTransaction().commit();
				session.clear();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		session.close();
	}

	/**
	 * 周日下午7点更新机构持股
	 * 
	 */
	@Transactional
	@Scheduled(cron = "0 0 9 ? * SUN")
	// @Scheduled(cron = "0 47 14 * * *")
	@Override
	public void addJGCG() {
		Session session = ContextUtil.getSessionFactory1().openSession();
		String sql = "select DISTINCT(code),t.diqv from Stock t ";
		List<Object[]> list = session.createQuery(sql).list();
		// session.beginTransaction();
		// String sqld = "delete from stock_gai_nian where 1=1";
		// session.createSQLQuery(sqld).executeUpdate();
		// session.getTransaction().commit();
		// session.clear();

		String sql1 = "from StockGaiNian t where t.code = ?0 ";
		session.beginTransaction();
		for (int i = 0; i < list.size(); i++) {

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				Object[] obj = list.get(i);
				System.out.println(obj[0]);
				StockGaiNian sg = (StockGaiNian) session.createQuery(sql1).setParameter(0, obj[0]).uniqueResult();

				System.out.println("更新机构持股比例：" + obj[0]);
				if (sg == null) {
					continue;
				}
				// StockGaiNian sg = new StockGaiNian();
				sg.setCode(obj[0] + "");
				String code = "";
				if ("0".equals(obj[1])) {
					code = "sh" + obj[0];
				} else {
					code = "sz" + obj[0];
				}
				String[] allgn = getJGCGBL(code);
				sg.setJgcount(Integer.valueOf(allgn[0]));
				sg.setJgbi(Float.valueOf(allgn[1]));
				sg.setCreateTime(DateTools.getCurrentDateTime());
				session.update(sg);

			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	/**
	 * 此方案主要用于更新所有股票的市值了。
	 */
	@Transactional
	//@Scheduled(cron = "0 0 11 ? * SAT")
	// @Scheduled(cron = "0 */2 * * * ?")
	@Override
	// @Scheduled(cron = "0 23 19 * * *")
	public void addGNShiZhi() {

		JSONArray list = stockselect.getStockCT6();
		List<String> lists = new ArrayList<String>();
		String all = "";

		System.out.println("数据库共：" + list.size());
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = list.getJSONObject(i);
			String diqv = json.getString("diqv");
			String code = json.getString("code");
			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			if (i % 500 == 0 && i != 0) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				all = "";
				continue;
			}
			if (i == list.size() - 1) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				break;
			}
			all += code + ",";
		}
		JSONArray jsonall = new JSONArray();
		for (int i = 0; i < lists.size(); i++) {
			JSONArray jsona = StockContrl.getCcc(lists.get(i), -1000f);
			jsonall.addAll(jsona);
		}

		System.out.println("共有股票" + jsonall.size());

		String sql1 = "update stock_gai_nian set shizhi = ?0 and t.huanshoulv = ?1 where code = ?2";

		Session session = ContextUtil.getSessionFactory1().openSession();
		session.beginTransaction();
		System.out.println("---开始市值运算---");
		for (int i = 0; i < jsonall.size(); i++) {
			JSONObject json = jsonall.getJSONObject(i);

			String code = json.getString("code");

			code = code.replace("sh", "").replace("sz", "");

			float shizhi = 0f;
			float huanshoulv = 0f;
			try {
				shizhi = Float.parseFloat(json.getString("shizhi"));
				huanshoulv = Float.parseFloat(json.getString("huanshoulv"));
			} catch (Exception e) {
				System.out.println("加载所有市值接口：转换市值字段报错");
			}

			System.out.println(code + "==" + shizhi);
			session.createSQLQuery(sql1).setParameter(0, shizhi).setParameter(1, huanshoulv).setParameter(2, code).executeUpdate();
		}
		System.out.println("---结束市值运算---");
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	public static WebDriver driver = null;

	public static WebDriver getdriver() {

		if (driver == null) {
			File f = new File("D:\\chromedriver\\chromedriver-win64124");
			if (f.exists()) {
				System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver-win64124\\chromedriver-win64\\chromedriver.exe");
			} else {
				System.setProperty("webdriver.chrome.driver", "/opt/chromedriver-linux64/chromedriver");
			}
			// 指定Chrome浏览器核心

			// 创建Chrome浏览器驱动
			// 配置Chrome选项
			ChromeOptions options = new ChromeOptions();
			options.addArguments("--headless"); // 无界面运行
			options.addArguments("--no-sandbox");
			options.addArguments("--disable-gpu");
			options.addArguments("--disable-dev-shm-usage");
			// 创建Chrome浏览器驱动
			driver = new ChromeDriver(options);
		}
		return driver;
	}

	public String[] getGN(String code) {
		String[] all = new String[] { "", "" };
		try {

			String url = "https://emweb.securities.eastmoney.com/pc_hsf10/pages/index.html?type=web&code=" + code + "&color=b#/hxtc/tcld";
			if (driver == null) {
				driver = getdriver();
			}
			driver.get(url);

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);
			// 抓取网页内容
			// String pageContent = driver.getPageSource();

			List<WebElement> elements = driver.findElements(By.xpath("//div[@class='gntc_content']//ul[@class='board']//li"));

			// 获取标签内容
			for (WebElement element : elements) {
				String[] tagContent = element.getText().split(" ");
				all[0] += tagContent[0] + ",";
			}

			List<WebElement> elements1 = driver.findElements(By.xpath("//div[@class='stockName']"));
			// 获取标签内容
			for (WebElement element : elements1) {
				String tagContent = element.getText();
				all[1] += tagContent + ",";
			}
			List<WebElement> elements2 = driver.findElements(By.xpath("//li[@class='boardName']"));
			for (int i = 0; i < elements2.size(); i++) {
				if (i == 1) {
					break;
				}
				all[0] += (elements2.get(i).getText().replace("行业", "").trim());
				System.out.println(all[0]);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("调用发生错误");
		}
		return all;
	}

	/**
	 * 查询机构持续比例
	 * 
	 * @param code
	 * @return
	 */
	public String[] getJGCGBL(String code) {
		String[] all = new String[] { "", "" };
		try {

			String url = "https://emweb.securities.eastmoney.com/pc_hsf10/pages/index.html?type=web&code=" + code + "&color=b#/gdyj/jgcc";
			if (driver == null) {
				driver = getdriver();
			}
			driver.get(url);
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);
			// 抓取网页内容
			// String pageContent = driver.getPageSource();
			WebElement element = driver.findElement(By.xpath("//div[@class='jgmx_content']//tr[@class='pointer active']"));
			List<WebElement> elements = element.findElements(By.xpath("./following-sibling::tr"));

			for (int i = 0; i < elements.size(); i++) {
				if (i == elements.size() - 1) {
					List<WebElement> elements1 = elements.get(i).findElements(By.tagName("td"));
					for (int j = 0; j < elements1.size(); j++) {
						// System.out.println(elements1.get(j).getText());
						String tdtxt = elements1.get(j).getText();
						if (j == 1) {
							all[0] = tdtxt.replace("(更新中)", "");
						}
						if (j == 4) {
							all[1] = tdtxt.replace("%", "");
						}
					}

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("调用发生错误");
		}
		return all;
	}

	/**
	 * 
	 * 
	 * 更新所有股票的换手率
	 * 
	 * 
	 */
	@Transactional
	@Scheduled(cron = "0 51 17 * * ?")
	@Override
	public void getCJL() {

		LocalDate currentDate = LocalDate.now();

		// 获取前90天日期
		LocalDate previousDate = currentDate.minusDays(150);

		// 以6位整数格式表示日期
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
		String previousDateStr = previousDate.format(formatter);
		System.out.println(previousDateStr);
		String sqld = "delete from stock where date < " + previousDateStr;
		Session session = ContextUtil.getSessionFactory1().openSession();
		session.beginTransaction();
		session.createSQLQuery(sqld).executeUpdate();
		session.getTransaction().commit();
		session.clear();

		JSONArray list = stockselect.getStockCT5();
		List<String> lists = new ArrayList<String>();
		String all = "";
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = list.getJSONObject(i);
			String diqv = json.getString("diqv");
			String code = json.getString("code");
			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			if (i % 500 == 0 && i != 0) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				all = "";
				continue;
			}
			if (i == list.size() - 1) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				break;
			}
			all += code + ",";
		}
		JSONArray jsonall = new JSONArray();
		for (int i = 0; i < lists.size(); i++) {
			JSONArray jsona = getCcc(lists.get(i));
			jsonall.addAll(jsona);
		}
		System.out.println(jsonall.size());
		String sql = "update stock t set t.huanshoulv = ?0 where t.code = ?1 and t.date = ?2";

		for (int i = 0; i < jsonall.size(); i++) {
			session.beginTransaction();
			JSONObject json = jsonall.getJSONObject(i);
			String date = json.getString("date").substring(0, 8);
			String code = json.getString("code").replace("sh", "").replace("sz", "");
			System.out.println(i + "=更新当天价格=" + date + "==" + code);
			String huanshoulv = json.getString("huanshoulv");
			session.createSQLQuery(sql).setParameter(0, huanshoulv).setParameter(1, code).setParameter(2, date).executeUpdate();
			session.getTransaction().commit();
			session.clear();
		}

		session.close();
	}

	public JSONArray getCcc(String codearr) {

		JSONArray jsonarrr = new JSONArray();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet("http://qt.gtimg.cn/q=" + codearr);
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] arary = codearr.split(",");
		try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String responseData = EntityUtils.toString(entity);
				// 对返回的responseData进行处理
				String[] str = responseData.split(";");
				for (int i = 0; i < str.length; i++) {
					String[] str1 = str[i].split("~");
					if (str1.length <= 1) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("name", str1[1]);
					json.put("code", arary[i]);
					json.put("zhangdiefu", str1[32]);
					json.put("huanshoulv", str1[38]);
					json.put("shizhi", str1[45]);
					json.put("date", str1[30]);
					jsonarrr.add(json);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jsonarrr;
	}

	@Override
	public void addNote(JSONArray json) {
		// TODO Auto-generated method stub
		String sql = "update stock_code set note1=?0 name=?1 date=?2 where code = ?3";
		Session session = ContextUtil.getSessionFactory1().openSession();
		for (int i = 0; i < json.size(); i++) {
			JSONObject jsonobject = json.getJSONObject(i);
			session.beginTransaction();
			session.createSQLQuery(sql).setParameter(0, jsonobject.getString("note1")).setParameter(1, jsonobject.getString("name")).setParameter(2, jsonobject.getString("date")).setParameter(3, jsonobject.getString("code")).executeUpdate();
			session.getTransaction().commit();
			session.clear();
		}
		session.close();
	}

	@Override
	public void addstockpcitrue(List<StockPcitrue> list) {
		// TODO Auto-generated method stub
		LocalDate currentDate = LocalDate.now();
		// 以6位整数格式表示日期
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		String previousDateStr = currentDate.format(formatter);
		Session session = ContextUtil.getSessionFactory1().openSession();
		session.beginTransaction();
		for (int i = 0; i < list.size(); i++) {
			StockPcitrue sp = list.get(i);
			sp.setDate(previousDateStr);
			session.save(sp);
		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	@Override
	public List<String> getdisSp() {
		// TODO Auto-generated method stub
		String sql = "select DISTINCT(t.sp) from stock_pcitrue t";
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<String> list = session.createSQLQuery(sql).list();
		return list;
	}

	@Override
	public List<StockPcitrue> getdisSp(String parameter) {
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();
		String sql = "from StockPcitrue t where t.sp = ?0";
		List<StockPcitrue> list = session.createQuery(sql).setParameter(0, parameter).list();
		session.clear();
		session.close();
		return list;
	}

	/**
	 * 正高标
	 */
	@Override
	public JSONArray getstockd(String day, String zuixiaohuanshou, String zuixiaozhangdiefu, String zongzhangdiefu) {

		JSONArray list = new JSONArray();
		String sql = "select * from (SELECT *,MIN(huanshoulv) as minh,min(zhandifu) as minz ,sum(zhandifu) as sumz" + "            FROM (" + "                SELECT *," + "                             ROW_NUMBER() OVER (PARTITION BY code ORDER BY date desc) AS row_num " + "                FROM stock" + "        ) AS sub_query WHERE row_num <= ?0  GROUP BY code) as hh WHERE  minh >=?1 and minz >=?2 and sumz<?3 ";
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list1 = session.createSQLQuery(sql).setParameter(0, day).setParameter(1, zuixiaohuanshou).setParameter(2, zuixiaozhangdiefu).setParameter(3, zongzhangdiefu).list();
		DecimalFormat df = new DecimalFormat("#00.00");

		for (int i = 0; i < list1.size(); i++) {
			Object[] obj = list1.get(i);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("zhandifu", df.format(Double.parseDouble(obj[8] + "")));
			// jsonObject.put("table_id", obj[0]);
			// jsonObject.put("chengjiaoliang", obj[1]);
			if ("0".equals(obj[5] + "")) {
				jsonObject.put("code", "sh" + obj[2]);
			} else {
				jsonObject.put("code", "sz" + obj[2]);
			}
			jsonObject.put("jiage", df.format(obj[3]));
			// jsonObject.put("date", obj[4]);
			// jsonObject.put("diqv", obj[5]);
			//
			jsonObject.put("name", obj[7]);
			if (obj[6] != null) {
				jsonObject.put("huanshoulv", df.format(Double.parseDouble(obj[6] + "")));
			}
			jsonObject.put("shizhi", "0");
			// jsonObject.put("note1", obj[9]);
			// jsonObject.put("create_time", obj[10]);
			// jsonObject.put("row_num", obj[11]);
			jsonObject.put("minh", df.format(Double.parseDouble(obj[12] + "")));
			jsonObject.put("minz", df.format(Double.parseDouble(obj[13] + "")));
			jsonObject.put("sumz", df.format(Double.parseDouble(obj[14] + "")));
			list.add(jsonObject);
		}
		return list;

	}

	/**
	 * 负高标
	 * 
	 */
	@Override
	public JSONArray getstockdf(String day, String zuixiaohuanshou, String zuixiaozhangdiefu, String zongzhangdiefu) {
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();

		JSONArray list = new JSONArray();
		String sql = "select * from (SELECT *,MIN(huanshoulv) as minh,max(zhandifu) as minz ,sum(zhandifu) as sumz" + "            FROM (" + "                SELECT *," + "                             ROW_NUMBER() OVER (PARTITION BY code ORDER BY date desc) AS row_num " + "                FROM stock" + "        ) AS sub_query WHERE row_num <= ?0  GROUP BY code) as hh WHERE  minh >=?1 and minz <=?2 ";

		List<Object[]> list1 = session.createSQLQuery(sql).setParameter(0, day).setParameter(1, zuixiaohuanshou).setParameter(2, zuixiaozhangdiefu).list();
		DecimalFormat df = new DecimalFormat("#00.00");

		for (int i = 0; i < list1.size(); i++) {
			Object[] obj = list1.get(i);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("zhandifu", df.format(Double.parseDouble(obj[8] + "")));
			// jsonObject.put("table_id", obj[0]);
			// jsonObject.put("chengjiaoliang", obj[1]);
			if ("0".equals(obj[5] + "")) {
				jsonObject.put("code", "sh" + obj[2]);
			} else {
				jsonObject.put("code", "sz" + obj[2]);
			}
			jsonObject.put("jiage", df.format(obj[3]));
			// jsonObject.put("date", obj[4]);
			// jsonObject.put("diqv", obj[5]);
			//
			jsonObject.put("name", obj[7]);
			if (obj[6] != null) {
				jsonObject.put("huanshoulv", df.format(Double.parseDouble(obj[6] + "")));
			}
			jsonObject.put("shizhi", "0");
			// jsonObject.put("note1", obj[9]);
			// jsonObject.put("create_time", obj[10]);
			// jsonObject.put("row_num", obj[11]);
			jsonObject.put("minh", df.format(Double.parseDouble(obj[12] + "")));
			jsonObject.put("minz", df.format(Double.parseDouble(obj[13] + "")));
			jsonObject.put("sumz", df.format(Double.parseDouble(obj[14] + "")));
			list.add(jsonObject);
		}
		return list;
	}

	@Override
	public JSONArray getstock2richaju(String chaju1, String zhangdiefu, String sumzhangdiefu) {

		List<String> list_0 = new ArrayList<String>();

		Session session = ContextUtil.getSessionFactory1().openSession();

		String sql0 = " SELECT code, date, huanshoulv  " + " FROM ( " + "    SELECT code, date, huanshoulv, " + "           ROW_NUMBER() OVER (PARTITION BY code ORDER BY date DESC) AS row_num " + "    FROM stock  " + " ) ranked " + " WHERE row_num = 1 or row_num =2 ";

		List<Object[]> list0 = session.createSQLQuery(sql0).list();

		for (int i = 0; i < list0.size(); i++) {
			Object[] obj = list0.get(i);
			String code = obj[0] + "";
			if (obj[2] == null) {
				continue;
			}
			Float f = Float.parseFloat(obj[2] + "");
			if (i == list0.size() - 1) {
				break;
			}
			Object[] obj1 = list0.get(i + 1);
			String code1 = obj1[0] + "";
			if (obj1[2] == null) {
				continue;
			}
			if (!code.equals(code1)) {
				continue;
			}
			Float f1 = Float.parseFloat(obj1[2] + "");
			if (code.equals(code1) && f > f1 && f / f1 > Float.parseFloat(chaju1)) {
				list_0.add(code);
			}
		}

		System.out.println("list_0==" + list_0.size());

		// TODO Auto-generated method stub
		JSONArray list = new JSONArray();
		String sql = " SELECT t.*,max(t.huanshoulv) as maxh,min(t.huanshoulv) as minh,min(t.zhandifu)as minz,sum(t.zhandifu) as sumz " + " FROM (  " + "    SELECT code, table_id, date, huanshoulv,  " + "           ROW_NUMBER() OVER (PARTITION BY code ORDER BY date DESC) AS rn  " + "    FROM stock " + " ) AS ranked " + " JOIN stock AS t ON ranked.code = t.code AND ranked.table_id = t.table_id " + " WHERE ranked.rn <= 2 " + " GROUP BY t.code "
				+ " HAVING MAX(t.huanshoulv)/MIN(t.huanshoulv)>?0  and sumz <=?1 and t.zhandifu >=?2";

		List<Object[]> list1 = session.createSQLQuery(sql).setParameter(0, chaju1).setParameter(1, sumzhangdiefu).setParameter(2, zhangdiefu).list();
		DecimalFormat df = new DecimalFormat("#00.00");
		for (int i = 0; i < list1.size(); i++) {

			Object[] obj = list1.get(i);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("zhandifu", df.format(Double.parseDouble(obj[8] + "")));
			// jsonObject.put("table_id", obj[0]);
			// jsonObject.put("chengjiaoliang", obj[1]);

			if (!list_0.contains(obj[2])) {
				continue;
			}
			if ("0".equals(obj[5] + "")) {
				jsonObject.put("code", "sh" + obj[2]);
			} else {
				jsonObject.put("code", "sz" + obj[2]);
			}
			jsonObject.put("jiage", df.format(obj[3]));
			// jsonObject.put("date", obj[4]);
			// jsonObject.put("diqv", obj[5]);
			//
			jsonObject.put("name", obj[7]);
			if (obj[6] != null) {
				jsonObject.put("huanshoulv", df.format(Double.parseDouble(obj[6] + "")));
			}
			jsonObject.put("shizhi", "0");
			// jsonObject.put("note1", obj[9]);
			// jsonObject.put("create_time", obj[10]);
			// jsonObject.put("row_num", obj[11]);
			jsonObject.put("minh", df.format(Double.parseDouble(obj[11] + "")));
			jsonObject.put("minz", df.format(Double.parseDouble(obj[13] + "")));
			jsonObject.put("sumz", df.format(Double.parseDouble(obj[14] + "")));
			jsonObject.put("chaju", df.format(Double.parseDouble(obj[11] + "") / Double.parseDouble(obj[12] + "")));
			list.add(jsonObject);
		}
		return list;
	}

	// 计算15个交易内连续大于N天大于6%以上的股票。
	@Override
	// @Scheduled(cron = "0 */10 * * * ?")
	// @Scheduled(cron = "0 10 15 * * *")
	public void addJs15dayLianxu3day() {
		this.wuyongy = 0;
		this.youy = 0;
		System.out.println("计算15个交易内连续大于N天大于6%以上的股票。");
		// TODO Auto-generated method stub
		String sql = "select * from stock_gai_nian t where t.shizhi < 450 ";
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<StockGaiNian> list = session.createQuery("from StockGaiNian t where t.shizhi <= ?0 and t.shizhi>=?1 ").setParameter(0, 400f).setParameter(1, 40f).list();

		int numThreads = 20;
		int chunkSize = list.size() / numThreads;

		ExecutorService executor = Executors.newFixedThreadPool(numThreads);

		for (int i = 0; i < numThreads; i++) {
			final int start = i * chunkSize;
			final int end = (i == numThreads - 1) ? list.size() : (i + 1) * chunkSize;
			executor.execute(() -> processChunk(list.subList(start, end)));
			System.out.println("开启一个线程" + i);
		}
		executor.shutdown();

	}

	public static int wuyongy = 0;
	public static int youy = 0;

	private static void processChunk(List<StockGaiNian> chunk) {

		System.out.println("开始启动");
		Session session = ContextUtil.getSessionFactory1().openSession();

		int temp = 5;
		// 在这里对每个 chunk 进行需要的操作，比如计算用户的年龄等
		String sql2 = "select t.zhandifu from stock t where t.code = ?0 ORDER BY  t.date DESC   limit  5";

		// List<Float> list = session.createSQLQuery(sql2).setParameter(0,
		// stock.cdo).list();
		String sql3 = "from Stock15DaySF t where t.code = ?0";

		String sql4 = "select t.huanshoulv from stock t where t.code = ?0 ORDER BY  t.date DESC   limit 5 ";

		String sql5 = "select t.danqianjia from stock t where t.code = ?0 ORDER BY  t.date DESC   limit 15 ";

		DecimalFormat df = new DecimalFormat("#.##");
		session.beginTransaction();
		for (StockGaiNian stock : chunk) {
			System.out.println("Processing user: " + stock.code);
			List<Float> floatList = session.createSQLQuery(sql2).setParameter(0, stock.code).list(); // 涨跌幅
			List<Float> floatList1 = session.createSQLQuery(sql4).setParameter(0, stock.code).list();// 换手率
			List<Float> floatList2 = session.createSQLQuery(sql5).setParameter(0, stock.code).list();// 价格

			// boolean b = isListUseful(floatList); // 5个交易日总和上涨和下跌在-3 到3之间股票

			// boolean b1 = checkMaxMinFudu(floatList); // 5个交易的价格涨跌幅不得超过3.5和-3.5

			boolean b = checkZhangdi5(floatList); // 第一天涨3以下，第二天涨-3以上
			boolean b1 = checkValues5(floatList1); // 最近一个交易日是上一个交易的日5倍
			// boolean b2 = checkMaxMinCondition(floatList1).getBoolean("state"); //
			// 5个交易日内的换手率不能低于3%

			// boolean b3 = checkMaxMinRatio(floatList1); // 5天的最大换手率和最小换手率，不能超过1.3倍 （换手率横盘）

			// boolean b3 =isNumbersIncreasing(floatList1); //并且成交量越来越小，

			boolean b4 = checkCtcom(floatList); // 当前涨跌幅度小于0

			boolean b5 = checkSumBelow100(floatList1); // 总换手率高低于100

			// boolean b6 = checkValues(floatList1); // 换手率必须大于1

			// boolean b3 = checkSumRange(floatList);

			// boolean b2 = checkMaxMinCondition(floatList1).getBoolean("price");

			if (b1 && b) {
				System.out.println(stock.code + "==有用");
				StockServiceImpl.youy++;
				StockGaiNian sn = (StockGaiNian) session.createQuery("from StockGaiNian t where t.code = ?0").setParameter(0, stock.code).uniqueResult();
				String name = (String) session.createSQLQuery("select DISTINCT(name) from stock t where t.code = ?0 limit 0,1").setParameter(0, sn.getCode()).uniqueResult();
				Stock15DaySF cs15 = (Stock15DaySF) session.createQuery(sql3).setParameter(0, stock.code).uniqueResult();
				if (cs15 != null) {
					cs15.setCode(sn.getCode());
					cs15.setGn(sn.getGn());
					cs15.setName(name);
					cs15.setDqhuanshoulv(floatList.get(0));
					cs15.setMaxhuanshoulv(Collections.max(floatList1));
					Float f = Collections.min(floatList1);
					cs15.setMinhuanshoulv(f);
					float jzx = ((floatList1.get(0) - f) / f) * 100;
					cs15.setJulizuixiaohuanshoulv(jzx);
					cs15.setCreateTime(DateTools.getCurrentDate(""));
					cs15.setLt(sn.getLt());
					cs15.setIslongtou(0);
					cs15.setLtCreateTime(0);

					session.update(cs15);
				} else {
					Stock15DaySF s15 = new Stock15DaySF();
					s15.setCode(sn.getCode());
					s15.setGn(sn.getGn());
					s15.setName(name);
					s15.setDqhuanshoulv(floatList1.get(0));
					s15.setMaxhuanshoulv(Collections.max(floatList1));
					Float f = Collections.min(floatList1);
					s15.setMinhuanshoulv(f);
					float jzx = ((floatList1.get(0) - f) / f) * 100;
					s15.setJulizuixiaohuanshoulv(jzx);
					s15.setCreateTime(DateTools.getCurrentDate(""));
					s15.setLt(sn.getLt());
					s15.setIslongtou(0);
					session.save(s15);
				}

			} else {
				// System.out.println(stock.code + "==无用");
				StockServiceImpl.wuyongy++;
			}
		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	/**
	 * 价格波动小
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkZhangdi5(List<Float> floatList) {
		if (floatList == null || floatList.size() <= 0) {
			return false;
		}
		if (floatList.get(1) <= 3.5) {
			return true;
		}

		return false;
	}

	/**
	 * 成交量超过5倍
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkValues5(List<Float> floatList) {
		try {
			if (floatList == null || floatList.size() <= 0) {
				return false;
			}
			if (floatList.get(0) / floatList.get(1) >= 4) {
				return true;
			}
			return false;
		} catch (Exception e) {
			System.out.println("--有错误--");
			return false;
		}

	}

	/**
	 * 成交量有4天低于1%不要
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkValues(List<Float> floatList) {
		int count = 0;
		for (Float num : floatList) {
			if (num <= 1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 涨跌的波动小于一个区间
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkMaxMinFudu(List<Float> floatList) {

		if (floatList == null || floatList.size() <= 0) {
			return false;
		}
		for (int i = 0; i < floatList.size(); i++) {
			if (floatList.get(i) < -3.5 || floatList.get(i) > 3.5) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 涨跌的波动小于一个区间
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkMaxMinFudu1(List<Float> floatList) {

		if (floatList == null || floatList.size() <= 0) {
			return false;
		}
		for (int i = 0; i < floatList.size(); i++) {
			if (floatList.get(i) == null) {
				continue;
			}
			if (floatList.get(i) < 10f) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkSumBelow100(List<Float> floatList) {
		float sum = 0;
		for (Float num : floatList) {
			sum += num;
		}
		return sum < 100;
	}

	/**
	 * 当前涨跌，低于-1
	 * 
	 * @param floatList
	 * @return
	 */
	private static boolean checkCtcom(List<Float> floatList) {
		// TODO Auto-generated method stub'
		if (floatList == null || floatList.size() <= 0) {
			return false;
		}
		if (floatList.get(0) <= 0) {
			return true;
		}
		return false;
	}

	public static boolean isNumbersIncreasing(List<Float> numbers) {
		if (numbers.size() < 2) {
			return true;
		}

		for (int i = 1; i < numbers.size(); i++) {
			if (numbers.get(i) <= numbers.get(i - 1)) {
				return false;
			}
		}

		return true;
	}

	public static boolean checkSumRange(List<Float> floatList) {
		float sum = 0;
		for (Float num : floatList) {
			sum += num;
		}

		return (sum <= 4 && sum >= -2);
	}

	public static boolean isListUseful(List<Float> floatList) {
		int count = 0; // 计数器，用于记录连续大于6的值个数

		if (floatList == null || floatList.size() <= 0) {
			return false;
		}

		Float sum = 0f;
		for (Float num : floatList) {
			if (num == null) {
				return false;
			}
			sum += num;
		}
		if (sum >= -3 && sum <= 3) {
			return true;
		}

		return false; // 如果没有连续三个值大于6，则返回false
	}

	public static JSONObject checkMaxMinCondition(List<Float> floatList) {

		JSONObject json = new JSONObject();
		if (floatList == null || floatList.isEmpty()) {
			json.put("state", false);
			return json;
		}
		for (Float num : floatList) {
			if (num == null) {
				json.put("state", false);
				return json;
			}
			if (num < 3) {
				json.put("state", false);
				return json;
			}
		}
		json.put("state", true);

		return json;
	}

	/**
	 * 最大值不超最小值2倍
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkMaxMinRatio(List<Float> floatList) {
		if (floatList.isEmpty()) {
			return false; // 空列表满足条件
		}

		for (int i = 0; i < floatList.size(); i++) {

			if (floatList.get(i) == null) {
				return false;
			}
		}

		float max = Collections.max(floatList);
		float min = Collections.min(floatList);

		return max <= 1.3 * min;
	}

	@Override
	// @Scheduled(cron = "0 34 14 * * ?")
	// @Scheduled(cron = "0 30 17 * * *")
	public void day15LongTou() {

		System.out.println("开始龙头计算");
		String sql = " select  t.lt from stock_gai_nian t ";

		Session session = ContextUtil.getSessionFactory1().openSession();

		List<String> list = session.createSQLQuery(sql).list();

		StringBuffer str = new StringBuffer();

		for (int i = 0; i < list.size(); i++) {
			str.append(list.get(i));
		}
		// 将字符串按逗号分割为数组
		String[] items = str.toString().split(",");

		// 使用 Set 来去除重复项
		Map<String, Integer> frequencyMap = new HashMap<>();
		for (String item : items) {
			if (frequencyMap.containsKey(item)) {
				frequencyMap.put(item, frequencyMap.get(item) + 1);
			} else {
				frequencyMap.put(item, 1);
			}
		}

		String sql1 = "from Stock15DaySF t where t.name = ?0 ";
		session.getTransaction().begin();
		for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {

			String key = entry.getKey();
			int value = entry.getValue();
			System.out.println("code:" + key + "ci" + value);
			Stock15DaySF s15 = (Stock15DaySF) session.createQuery(sql1).setParameter(0, key).uniqueResult();
			if (s15 != null) {
				s15.setIslongtou(value);
				s15.setLtCreateTime(Integer.parseInt(DateTools.getCurrentDate("")));
				session.update(s15);
			}
		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	/**
	 * 增加公司的产品和行业和业绩
	 */
	@Override
	/**
	 * 此方案主要用于更新所有股票的市值了。
	 */
	@Transactional
	@Scheduled(cron = "0 30 16 ? * SAT")
	public void addChanping() {

		Session session = ContextUtil.getSessionFactory1().openSession();
		String sql = "select DISTINCT(code),t.diqv from Stock t ";
		List<Object[]> list = session.createQuery(sql).list();

		String sql1 = "from StockGaiNian t where t.code = ?0";
		for (int i = 0; i < list.size(); i++) {

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				Object[] obj = list.get(i);
				System.out.println(obj[0]);
				session.beginTransaction();
				StockGaiNian sg = (StockGaiNian) session.createQuery(sql1).setParameter(0, obj[0]).uniqueResult();
				sg.setCode(obj[0] + "");
				String code = "";
				if ("0".equals(obj[1])) {
					code = "sh" + obj[0];
				} else {
					code = "sz" + obj[0];
				}
				String[] allgn = TestHangYe.getCP(code);
				String[] allyj = TestYinShou.getYJ(code);
				System.out.println(allgn.toString());
				sg.setHy(allgn[0]);
				sg.setCp(allgn[1]);
				sg.setQy(allgn[2]);
				sg.setYs(allyj[0]);
				sg.setJlr(allyj[1]);
				session.merge(sg);
				session.getTransaction().commit();
				session.clear();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		session.close();

	}

	@Override
	public List<String> getallCode() {
		// TODO Auto-generated method stub
		String sql = "select DISTINCT(code),diqv from stock  ";

		Session session = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session.createSQLQuery(sql).list();

		List<String> list1 = new ArrayList<String>();

		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			String code = obj[0] + "";
			String diqv = obj[1] + "";

			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			list1.add(code);
		}
		return list1;
	}

	@Override
	public List<String> getallCode1(JSONObject json) {
		// TODO Auto-generated method stub
		String sql = "select DISTINCT(code),diqv from stock   where code in (?0) ";

		String[] list0 = json.getString("textarea1").split(",");
		List<String> list2 = Arrays.asList(list0);
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session.createSQLQuery(sql).setParameterList(0, list2).list();

		List<String> list1 = new ArrayList<String>();

		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			String code = obj[0] + "";
			String diqv = obj[1] + "";

			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			list1.add(code);
		}
		return list1;
	}

	@Override
	public void addLTmodel(JSONObject json) {
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();
		LTModel lt = (LTModel) json.toBean(json, LTModel.class);
		session.beginTransaction();
		session.save(lt);
		session.flush();
		session.clear();
		session.close();

	}

	@Override
	public JSONArray getLt() {
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();

		List<LTModel> list = session.createQuery("from LTModel t order by t.group1 desc").list();

//		List<Object[]> objlist = session.createSQLQuery("select DISTINCT(code1),t1.diqv from ltmodel t  left join stock t1 on t.code1  = t1.code ").list();
//
//		for (int i = 0; i < objlist.size(); i++) {
//			Object[] obj = objlist.get(i);
//			for (int j = 0; j < list.size(); j++) {
//				if (obj[0].equals(list.get(j).getCode1())) {
//					list.get(i).setDiqv(obj[1] + "");
//					continue;
//				}
//			}
//		}

		return JSONArray.fromObject(list);
	}

	@Override
	public void deleteLTmodel(JSONObject json) {
		Session session = ContextUtil.getSessionFactory1().openSession();
		session.beginTransaction();

		if (null == json.getString("code1") || "".equals(json.getString("code1"))) {
			session.createSQLQuery("delete from ltmodel where  group1='" + json.getString("group1") + "'").executeUpdate();

		} else {
			session.createSQLQuery("delete from ltmodel where code1 = '" + json.getString("code1") + "' and group1='" + json.getString("group1") + "'").executeUpdate();

		}
        session.getTransaction().commit();
		session.flush();
		session.clear();
		session.close();

	}

	@Override
	public List<String> getallGNCode(JSONObject json) {
		// TODO Auto-generated method stub
		return null;
	}

}
